package view.listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JTextField;

import model.Constants;
import model.HostAddress;
import model.IPAddress;
import view.components.IPTextArea;
import view.dialogs.AddHostDialog;
import view.dialogs.InfoDialog;
import controller.Calculator;
import controller.Controller;

public class AddHostListener implements ActionListener {

	private final AddHostDialog addHost;
	private final IPTextArea ipText;
	private final JTextField nameText;

	public AddHostListener(AddHostDialog addHost, IPTextArea ipText,
			JTextField nameText) {
		this.addHost = addHost;
		this.ipText = ipText;
		this.nameText = nameText;
	}

	@Override
	public void actionPerformed(ActionEvent e) {


		boolean exists = false;

		ArrayList<HostAddress> hosts = Controller.getInstance().getHosts();

		if (Calculator.getInstance().validateIpTextArea(ipText)) {

		String ip = Calculator.getInstance().getIpFromIpTextArea(ipText);
		String s = nameText.getText();

		if (s.equals(Constants.EMPTY) || s.equals(null)) {
			s = ip;
		}

		for (HostAddress hostAddress : hosts) {
			if (hostAddress.getHostAddress().getAddress().equals(ip)) {
				new InfoDialog(Constants.ERROR, Constants.HOSTEXISTS);
				exists = true;
			}
		}

		if (!exists) {
			HostAddress newHost = new HostAddress(new IPAddress(ip), s);

			if (Calculator.getInstance().validateAddress(
					newHost.getHostAddress().getAddress())) {

				hosts.add(newHost);
					Controller.getInstance().setHosts(hosts);

			} else {
				new InfoDialog(Constants.ERROR, Constants.ADDRESSEXISTS);
			}
		}

		addHost.dispose();
		} else {
			new InfoDialog(Constants.ERROR, Constants.WRONGNUMBERS);
		}
	}


}
